package connect4client.commands;

import game.Player;

import java.util.List;

import util.Pair;

import messages.MatchEndedMessage;
import connect4client.core.GameManager;
import connect4client.core.PlayerManager;
import connect4client.user.User;

/**
 * The MatchEnded command.
 * 
 * This command will handle MatchEnded messages.
 */
public class MatchEndedCommand extends Command {

	public MatchEndedCommand(MatchEndedMessage matchEndedMessage) {
		super(matchEndedMessage);
	}


	@Override
	public void execute() {
		GameManager gameManager = controller.getGameManager();
		PlayerManager playerManager = controller.getPlayerManager();
		
		MatchEndedMessage message = (MatchEndedMessage) this.message;
		int matchId = message.getMatchStatistics().getMatchId();
		String winner = message.getMatchStatistics().getWinner();

		synchronized (gameManager) {
			List<Pair<String, Integer>> list = message.getMatchStatistics().getScore();

			
			int score1 = list.get(0).getSecond();
			int score2 = list.get(1).getSecond();

			User me = controller.getUser();

			// Let's update the rankings
			List<Player> players = message.getPlayers();

			Player player1 = players.get(0);
			Player player2 = players.get(1);

			synchronized (playerManager) {
				if (player1.equals(me.getPlayer())) {
					me.setRanking(player1.getRanking());
					playerManager.getPlayerByLogin(player2.getLogin()).setRanking(player2.getRanking());
				} else if (player2.equals(me.getPlayer())) {
					me.setRanking(player2.getRanking());
					playerManager.getPlayerByLogin(player1.getLogin()).setRanking(player1.getRanking());
				} else {
					playerManager.getPlayerByLogin(player2.getLogin()).setRanking(player2.getRanking());
					playerManager.getPlayerByLogin(player1.getLogin()).setRanking(player1.getRanking());
				}
			}
			
			if (score1 == score2)
				guiMediator.matchEndedTied(matchId, message.getPlayers());
			else
				guiMediator.matchEnded(matchId, message.getPlayers(), winner);

			// Let's remove the match from the matchlist
			gameManager.removeMatch(matchId);
		}
	}

}
